package com.zpb.framework.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Api;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zpb.framework.domain.ApiResult;
import com.zpb.framework.domain.enums.ResultCodeEnum;
import com.zpb.framework.exception.SystemException;
import com.zpb.framework.service.UploadService;
import com.zpb.framework.utils.ImageChecker;
import com.zpb.framework.utils.PathUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;

/**
 * @Description:
 * @Author: zhaopengbo
 * @Date: 2025/9/14
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Override
    public ApiResult uploadImg(MultipartFile img) {
        // 判断文件类型
        if(!ImageChecker.isImage(img)){
            throw new SystemException(ResultCodeEnum.NOT_IMG);
        }

//        img.getSize();
        // 如果判断通过上传文件到oss
        String url = uploadOss(img);
        return ApiResult.success(url);
    }

    @Value("${qiniu.oss.accessKey}")
    private String accessKey;
    @Value("${qiniu.oss.secretKey}")
    private String secretKey;
    @Value("${qiniu.oss.bucket}")
    private String bucket;
    @Value("${qiniu.oss.domain}")
    private String domain;

    public String uploadOss(MultipartFile file) {
//构造一个带指定 Region 对象的配置类
        Configuration cfg = Configuration.create(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = PathUtils.generateFilePath(Objects.requireNonNull(file.getOriginalFilename()));
//http://t2iuvwvr2.hb-bkt.clouddn.com/2025/09/14/71f6c977c6944609b96d3fc1ae5612a9.jpg
        try {

            InputStream fis = file.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(fis, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                System.out.println(putRet.key);
                System.out.println(putRet.hash);

            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);
                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url = domain + key;
        return url;
    }
}
